from sklearn.datasets import load_breast_cancer
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
import numpy as np
import pandas as pd

dataset = load_breast_cancer()
x,y = load_breast_cancer() .data,load_breast_cancer().target
print(x.shape)
print(x)

#数据标准化
from sklearn.preprocessing import StandardScaler
x = StandardScaler().fit_transform(x)
print(x)

#分割数据集
from sklearn.metrics import accuracy_score

x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=420)
kernel_list = ["linear", "poly", "rbf", "sigmoid"]
for kernel in kernel_list:
    model = SVC(kernel=kernel, gamma="auto", degree=1)
    model.fit(x_train, y_train)
    pred = model.predict(x_test)
    y_test_flat = y_test.ravel()
    ac = accuracy_score(y_test_flat, pred)
    print("选择%s核函数时，模型的预测准确率为%f" % (kernel, ac))

from sklearn.datasets import load_breast_cancer
#导入肺癌数据集
from sklearn.svm import SVC         #导入支持向量机分类模块
from sklearn.model_selection import train_test_split
import numpy as np
from sklearn.preprocessing import StandardScaler
x,y=load_breast_cancer().data,load_breast_cancer().target
x=StandardScaler().fit_transform(x) #数据标准化处理

from sklearn.model_selection import StratifiedShuffleSplit
#导入分层抽样方法
from sklearn.model_selection import GridSearchCV
#导入网格搜索方法
gamma_range=np.logspace(-10,1,20)
coef0_range=np.linspace(0,5,10)
param_grid=dict(gamma=gamma_range,coef0=coef0_range)
cv=StratifiedShuffleSplit(n_splits=5,test_size=0.3,
random_state=420)                   #对样本进行分层抽样
grid=GridSearchCV(SVC(kernel="poly",degree=1),
param_grid=param_grid,cv=cv)        #使用网格搜索法寻找参数的最优值
grid.fit(x,y)
print("最优参数值为：%s"%grid.best_params_)
print("选取该参数值时，模型的预测准确率为：%f"%grid.best_score_)

from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3,random_state=420)  #分割数据集
score=[]
gamma_range=np.logspace(-10,1,50)
for i in gamma_range:
    model=SVC(kernel='rbf',gamma=i)
    model.fit(x_train,y_train)
    pred=model.predict(x_test)
    ac=accuracy_score(y_test,pred)
    score.append(ac)
#画曲线图，横轴为gamma值，纵轴为对应模型的预测准确率
plt.plot(gamma_range,score)
plt.show()
#输出模型的最大预测准确率与对应的gamma值
print("参数gamma的最优值为：%s"%gamma_range[score.index(max(score))])
print("选取该参数值时，模型的预测准确率为：%f"%max(score))

from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3,random_state=420)

score=[]
C_range=np.linspace(0.01,30,50)
for i in C_range:
    model=SVC(kernel='linear',C=i)  # 补全缺失的右括号
    model.fit(x_train,y_train)
    pred=model.predict(x_test)
    ac=accuracy_score(y_test,pred)
    score.append(ac)

# 画曲线图，横轴为 C 值，纵轴为对应模型的预测准确率
plt.plot(C_range,score)
plt.show()

# 输出模型的最大预测准确率与对应的 C 值
print("模型的最优 C值为：%s"%C_range[score.index(max(score))])
print("模型选取该参数时的预测准确率为：%f"%max(score))